﻿using System.Web.Mvc;
using Web7.Core.Apps;
using Web7.Core.Extensions;
using Web7.Core.Security;

namespace Web7.Core.ActionFilters.Authorization
{
    public class AuthorizationFilter : IAuthorizationFilter
    {
        private readonly IDependencyResolver _dependencyResolver;
        private readonly IAppRegistry _appsLoaded;
        private readonly IUser _user;

        public AuthorizationFilter() : this(DependencyResolver.Current) { }

        public AuthorizationFilter(IDependencyResolver dependencyResolver)
        {
            this._dependencyResolver = dependencyResolver;
            this._appsLoaded = dependencyResolver.GetService<IAppRegistry>();
            this._user = dependencyResolver.GetService<IUser>();
        }

        #region IAuthorizationFilter Members

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //当前用户
            IUser user = _dependencyResolver.GetService<IUser>();

            if (user == null || !user.IsAuthenticated)
            {
                //当前模块的认证模块
                IAuthenticationApp authenticationModule = _dependencyResolver.GetService<IAuthenticationApp>();
                if (authenticationModule == null)
                    throw new System.Exception("AuthenticationModule of current module is null.");
                string signInUrl = authenticationModule.GetSignInUrl(filterContext.RequestContext);
                filterContext.SetActionResult(signInUrl);
            }
        }

        #endregion
    }
}
